<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //扁平数据与树结构的相互转换
      var data = [
        { id: 1, pid: 0, name: "沃尔玛" },
        { id: 2, pid: 0, name: "生鲜区" },
        { id: 3, pid: 1, name: "日用品区" },
        { id: 4, pid: 2, name: "鱼" },
        { id: 5, pid: 2, name: "牛肉" },
        { id: 6, pid: 3, name: "卫生纸" },
        { id: 7, pid: 3, name: "牙刷" },
        { id: 8, pid: 7, name: "电动牙刷" },
        { id: 9, pid: 7, name: "普通牙刷" },
      ];

      function setTreeData(source) {
        let cloneData = JSON.parse(JSON.stringify(source)); // 对源数据深度克隆
        return cloneData.filter((father) => {
          // 循环所有项，并添加children属性
          let branchArr = cloneData.filter((child) => father.id == child.pid); // 返回每一项的子级数组
          branchArr.length > 0 ? (father.children = branchArr) : ""; //给父级添加一个children属性，并赋值
          return father.pid == 0; //返回第一层
        });
      }
      console.log(setTreeData(data));
      //
      //
      //
      const tree = [
        { id: "1", rank: 1 },
        {
          id: "2",
          rank: 1,
          children: [
            { id: "2.1", rank: 2 },
            { id: "2.2", rank: 2 },
          ],
        },
        {
          id: "3",
          rank: 1,
          children: [
            {
              id: "3.1",
              rank: 2,
              children: [
                {
                  id: "3.1.1",
                  rank: 3,
                  children: [
                    {
                      id: "3.1.1.1",
                      rank: 4,
                      children: [{ id: "3.1.1.1.1", rank: 5 }],
                    },
                  ],
                },
              ],
            },
          ],
        },
      ];
      function flattenArr(tree, arr = []) {
        tree.forEach((item) => {
          const { children, ...otherProps } = item;
          // 添加除了children的属性
          arr.push(otherProps);
          if (children) {
            // 递归将所有节点加入到结果集中
            flattenArr(children, arr);
          }
        });
        return arr;
      }
      console.log(flattenArr(tree));
    </script>
  </body>
</html>
